package com.caigou.comm.base.utils

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author #Suyghur.
 * Created on 2022/01/06
 */
object MediaUtils {

    fun saveBitmap(context: Context, bitmap: Bitmap) {
        val dir = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Camera")
        } else {
            context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        }

        dir?.apply {
            if (!exists()) {
                mkdirs()
            }
            val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault())
            val date = Date(System.currentTimeMillis())
            val fileName = simpleDateFormat.format(date)
            val path = File(dir, "$fileName.jpg")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                saveImage29(context, bitmap)
            } else {
                saveImage(context, path, bitmap)
            }
        }
    }

    private fun saveImage(context: Context, path: File, bitmap: Bitmap) {
        var out: FileOutputStream? = null
        try {
            out = FileOutputStream(path)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
            refreshFile(context, path)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } finally {
            if (out != null) {
                try {
                    out.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    private fun saveImage29(context: Context, bitmap: Bitmap) {
        val uri = insertImage(context, null)
        val contentResolver = context.contentResolver
        var parcelFileDescriptor: ParcelFileDescriptor? = null
        try {
            parcelFileDescriptor = contentResolver.openFileDescriptor(uri, "w")
            if (parcelFileDescriptor == null) {
                return
            }
            val outputStream = FileOutputStream(parcelFileDescriptor.fileDescriptor)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (parcelFileDescriptor != null) {
                try {
                    parcelFileDescriptor.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    private fun insertImage(context: Context, image: File?): Uri {
        val values = ContentValues()
        values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg")
        image?.apply {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, parentFile.name)
                values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, lastModified())
            } else {
                values.put(MediaStore.Images.ImageColumns.DATA, path)
            }
        }
        return context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)!!
    }

    private fun refreshFile(context: Context, file: File) {
        val uri = Uri.fromFile(file)
        val handler = Handler(Looper.getMainLooper())
        handler.post {
            val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            intent.data = uri
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            context.sendBroadcast(intent)
        }
    }
}